package com.cherish.config.security.detailservice;

import com.cherish.web.menu.entity.Menu;
import com.cherish.web.menu.service.MenuService;
import com.cherish.web.user.entity.User;
import com.cherish.web.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Author:MQ
 * Date:2023/12/2322:13
 * 自定义UserDetailsService 用于认证和授权
 * 此处把用户的信息和权限交给spring security
 * spring security会对用户的信息和权限信息进行管理
 */
@Component("customerUserDetailsService")
public class CustomerUserDetailsService implements UserDetailsService {
    @Autowired
    private UserService userService;
    @Autowired
    private MenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.查询用户是否存在
        System.out.println(new Date() + "当前登录用户为" + username);
        User user = userService.getUserByUserName(username);

        if(user == null){
            throw new UsernameNotFoundException("用户名或密码错误!");
        }
        //2.授权
        //2.1 查询用户所有权限
        List<Menu> menuList = menuService.getMenuListByUserId(user.getFId());
        //2.2 获取所有的权限字段，即sys_permission表中的code字段
        List<String> collect = menuList.stream()
                .filter(item -> item != null)
                .map(item -> item.getFCode())
                .filter(item -> item != null).collect(Collectors.toList());
        //2.3 转换为数组
        String[] strings = collect.toArray(new String[collect.size()]);
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(strings);
        //2.4 设置权限
        user.setAuthorities(authorityList);
        //2.5 设置菜单列表
        user.setPermissionList(menuList);
        return user;
    }
}
